package com.hmall.common.mq;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;

@ConditionalOnProperty(
        value = "spring.rabbitmq.listener.simple.retry.enabled",
        havingValue = "true"
)
public class MqConsumeErrorAutoConfiguration {


    @Value("${spring.application.name}")
    private String applicationName;


    //创建RabbitMqHelper
    @Bean
    public RabbitMqHelper rabbitMqHelper(){
        return new RabbitMqHelper();
    }


    //创建交换机
    @Bean
    public DirectExchange errorDirect(){
        return new DirectExchange("error.direct");
    }
    //创建队列
    @Bean
    public Queue errorQueue(){
        return new Queue(applicationName+"error.queue");
    }
    //绑定
    @Bean
    public Binding dlxBinding(DirectExchange errorExchange, Queue errorQueue){
        return BindingBuilder.bind(errorQueue).to(errorExchange).with(applicationName);
    }

    //重试次数达上线处理策略
    @Bean
    public MessageRecoverer republishMessageRecoverer(RabbitTemplate rabbitTemplate){
        return new RepublishMessageRecoverer(rabbitTemplate,"error.direct",applicationName);
    }

}
